<template>
  <div class="chat-container">
    <!-- 消息显示区域 -->
    <div ref="chatBox" class="chat-box">
      <div v-for="(msg, index) in messages" :key="index" class="message">
        <div class="user-msg" v-if="msg.isUser">{{ msg.content }}</div>
        <div class="ai-msg" v-else>{{ msg.content }}</div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <textarea
        v-model="userInput"
        @keyup.enter="sendMessage"
        placeholder="请输入你的问题..."
      ></textarea>
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      messages: [],
      userInput: '',
      isLoading: false // 加载状态
    };
  },
  methods: {
    sendMessage() {
      if (!this.userInput.trim()) return;
      
      // 添加用户消息
      const userMsg = { isUser: true, content: this.userInput };
      this.messages.push(userMsg);
      // this.userInput = '';
      this.isLoading = true; // 显示加载状态

      // 调用普通POST请求
      this.fetchChatResponse(this.userInput);
    },

    fetchChatResponse(message) {
      axios.post('http://127.0.0.1:8000/api/chat/', { message })
        .then(response => {
                this.userInput = '';
          this.isLoading = false; // 结束加载
          if (response.data.success) {
            const aiContent = response.data.response.content;
            this.messages.push({ 
              isUser: false, 
              content: aiContent 
            });
            this.scrollToBottom(); // 滚动到底部
          } else {
            this.messages.push({ 
              isUser: false, 
              content: '抱歉，获取回复失败。' 
            });
          }
        })
        .catch(error => {
          this.isLoading = false;
          console.error('请求失败:', error);
          this.messages.push({ 
            isUser: false, 
            content: '抱歉，网络请求失败，请重试。' 
          });
        });
    },

    scrollToBottom() {
      this.$nextTick(() => {
        this.$refs.chatBox.scrollTop = this.$refs.chatBox.scrollHeight;
      });
    }
  }
};
</script>

<style scoped>
/* 样式保持不变，可添加加载状态样式 */
.chat-box {
  /* 原有样式 */
}

/* 可选：加载状态样式 */
.loading {
  padding: 10px;
  text-align: center;
  color: #666;
}
</style>